import { ref } from 'vue'
import { ElMessage } from 'element-plus';
import { useHandleData } from './useHandleData';

//定义弹框props参数
interface DialogProps {
    title: string;
    isView: boolean;
    rowData?: any;
    apiUrl?: (params: any) => Promise<any>;
    getTableList?: () => Promise<any>;
    callback?: (params: any) => Promise<any>;
}

/**
 * 弹框新增、修改公共部分
 */
export function useModal(formData: any, formRef: any, initialized: any) {
    const visible = ref(false);

    //缓存第一次加载的表单对象，用来缓存默认值
    const cacheFormData = Object.assign({}, formData);

    // drawer框状态
    const dialogData = ref<DialogProps>({
        isView: false,
        title: '',
    });

    // 接收父组件传过来的参数
    const acceptParams = (params: DialogProps) => {
        dialogData.value = params || {};
        visible.value = true;
        const rowData = dialogData.value.rowData;
        if(rowData) {
            for (let key in formData) {
                formData[key] = rowData[key] || cacheFormData[key]
            }
        }
        if(initialized && typeof initialized === 'function') {
            initialized();
        }
    }

    const handleSubmit = () => {
        formRef.value!.validate((valid) => {
            if (!valid) return;
            if (!dialogData.value.apiUrl) {
                ElMessage.error('未配置请求接口')
                return;
            }

            let submitData = formData//需要提交的表单
            if (dialogData.value.title === '编辑') {
                submitData = getSubmitData();
                if (Object.keys(submitData).length === 0) {
                    ElMessage.error('未做任何修改，不能进行提交')
                    return
                }
            }

            useHandleData(dialogData.value.apiUrl, { ...submitData, id: dialogData.value.rowData.id }, `${dialogData.value.title}`).then((res:any) => {
                if (res && res.data) {
                    dialogData.value.getTableList && dialogData.value.getTableList();
                    dialogData.value.callback && dialogData.value.callback({ ...formData, id: res.data.id });
                    visible.value = false;
                }
            })
        });
    }

    /**
     * 获取修改的字段
     * @returns 
     */
    const getSubmitData = (): any => {
        let submitData = {}
        for (let k in formData) {
            var item = formData[k]
            if (dialogData.value.rowData[k] != item) {
                submitData[k] = item
            }
        }
        return submitData
    }

    return {
        visible,
        acceptParams,
        handleSubmit,
        dialogData
    }

}